﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BIZMA._controls;
using BIZModel;

namespace BIZMA._controls.Messages
{
    public partial class List_Messages : System.Web.UI.UserControl, IModalDialog
    {
        public UC_ModalContainer ContainerControl { get; set; }
        private bool InitLoaded { get { return ViewState["InitLoaded"] != null ? (bool)ViewState["InitLoaded"] : false; } set { ViewState["InitLoaded"] = value; } }
        private bool CanAddPopupControl { get { return ViewState["CanAddPopupControl"] != null ? (bool)ViewState["CanAddPopupControl"] : false; } set { ViewState["CanAddPopupControl"] = value; } }

        //OLIKA ID properties som styr frågan för listan tex om man ska hämta utifrån EmployeeId eller PlanningId
        //Styrs av publika metoder
        private int SOMEVALPROP { get { return ViewState["SOMEVALPROP"] != null ? (int)ViewState["SOMEVALPROP"] : 0; } set { ViewState["SOMEVALPROP"] = value; } }
        private int SOMEVALPROP2 { get { return ViewState["SOMEVALPROP2"] != null ? (int)ViewState["SOMEVALPROP2"] : 0; } set { ViewState["SOMEVALPROP2"] = value; } }

        //Olika filter för frågan till listan kan tex vara om man ska visa alla eller aktiva, eller datum mmm
        //Filter sätter man innan man kör de publika metorder som sätter ID properties som finns ovan
        public int Filter_SOMEFILTER { get { return ViewState["Filter_SOMEFILTER"] != null ? (int)ViewState["Filter_SOMEFILTER"] : 0; } set { ViewState["Filter_SOMEFILTER"] = value; } }

        private Guid ImageTag { get { return ViewState["ImageTag"] != null ? (Guid)ViewState["ImageTag"] : Guid.Empty; } set { ViewState["ImageTag"] = value; } }

        #region This dialog
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack || !InitLoaded)
            {
                InitLoaded = true;

                //Gör sådant som man gör på pageload här typ fyll "statisk" dropdown med värden mm 
                //Väldigt ovanligt att man laddar listan härifrån då det oftast görs via en annan metod se public void LOAD_BY_SOMETHING_LIST(int someval)
            }

        }


        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            //här gör man alla init inställningar typ lägga till eventhandlers och annat som styr sidan

            if (ContainerControl != null)
            {
                ContainerControl.ShowButtons(false, false, false);
                ContainerControl.Title = "Meddelanden";
                ContainerControl.Width = 500;
                ContainerControl.Height = 800;
                ContainerControl.DOClick += new UC_ModalContainer.ModalCommand(Modal_DOClick);
                ContainerControl.OKClick += new UC_ModalContainer.ModalCommand(Modal_OKClick);
                ContainerControl.CancelClick += new UC_ModalContainer.ModalCommand(Modal_CancelClick);
            }

            CanAddPopupControl = Pop_NewMessage.CanAddPopupControl(ModalControls.Message);
           // BaseBL.BtnOpenEnabled(btnNew, CanAddPopupControl, ViewState);
        }



        void Modal_CancelClick(object sender, EventArgs e)
        {

        }

        void Modal_OKClick(object sender, EventArgs e)
        {

        }

        void Modal_DOClick(object sender, EventArgs e)
        {

        }

        #endregion
        #region list

        /// <summary>
        /// Här rensas alla id p
        /// roperties som används för frågan till listan
        /// </summary>
        private void ResetIdProperties()
        {
            SOMEVALPROP = 0;
            SOMEVALPROP2 = 0;
        }

        //Publika metoder som underliggande sida/kontroll kan ropa på för att ladda kontrollen
        //public void LOAD_BY_SOMETHING_LIST(int someval)
        //{
        //    ResetIdProperties();
        //    SOMEVALPROP = someval;
        //}

        //public void LOAD_BY_SOMETHING_ELSE_LIST(int someval2)
        //{
        //    ResetIdProperties();
        //    SOMEVALPROP2 = someval2;
        //}

        /// <summary>
        /// Listar alla meddelanden
        /// </summary>
        public void ListAllMessages()
        {
            LoadList(false);
        }


        public void LoadImageTagMessages(Guid imageTagId)
        {

            ImageTag = imageTagId;
            LoadList(false);
        }


        /// <summary>
        /// Metod som ansvarar för att fylla listan med värden utifrån vilken publik load metod som körts innan
        /// </summary>
        /// <param name="sorting">Talar om ifall sortering ska ändras eller om man ska använda tidigare sortering</param>
        private void LoadList(bool sorting)
        {
            InitLoaded = true;

            BIZMAEntities ent = BaseBL.GetEnt();

            IQueryable<Message> query = null;

            if (ImageTag != Guid.Empty)
            {
                query = ent.Messages.Where(q => q.ImageTags.FirstOrDefault(qs => qs.ImageTagId == ImageTag).Messages.FirstOrDefault().MessageId == q.DiscussionId).OrderByDescending(q => q.MessageDate);
            }
            else if (SOMEVALPROP2 > 0)
            {
                query = ent.Messages.Where(q => q.MessageId == q.DiscussionId).OrderByDescending(q => q.MessageDate);
            }
            else
            {
                query = ent.Messages.Where(q => q.MessageId == q.DiscussionId).OrderByDescending(q => q.MessageDate);
            }

            if (query != null)
            {
                if (Filter_SOMEFILTER != 0)
                {
                    query = query.Where(q => q.FromUserId == BaseBL.UserKey);
                }
            }


            lv.DataSource = query;
            lv.DataBind();

            //if (!sorting)
            //    lv.ReSort(ViewState);
        }

        protected void lv_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            //Här kan man kanske behöva göra speciella funktioner för varje rad i listan om vanliga databind inte fungerar
            //LinkButton lkb5 = (LinkButton)e.Item.FindControl("lkb5");
            //lkb5.Text = ((byte)DataBinder.Eval(e.Item.DataItem, "Debet")) == (byte)1 ? "Ja" : "Nej";
        }

        protected void lv_PagePropertiesChanged(object sender, EventArgs e)
        {
            LoadList(false);
        }

        protected void lv_Sorting(object sender, ListViewSortEventArgs e)
        {
            LoadList(true);
            ListView lv = (ListView)sender;
            lv.ListViewOrder(ViewState, e);
        }
        #endregion
        #region detail dialog
        protected void Reply(object sender, CommandEventArgs e)
        {
            if (CanAddPopupControl)
            {
                Pop_NewMessage.AddControl(ModalControls.Message);

                if (Pop_NewMessage.PopUpControlExists)
                {
                    Edit_Message uc = ((Edit_Message)Pop_NewMessage.PopUpControl);
                    uc.ReplyMessage(Guid.Parse(e.CommandArgument.ToString()));
                    Pop_NewMessage.ModalOpen();

                }
            }

        }

        protected void btnNew_Command(object sender, CommandEventArgs e)
        {
            if (CanAddPopupControl)
            {
                Pop_NewMessage.AddControl(ModalControls.Message);

                if (Pop_NewMessage.PopUpControlExists)
                {
                    Edit_Message uc = ((Edit_Message)Pop_NewMessage.PopUpControl);
                    uc.NewMessage();

                    uc.ImageTagId = ImageTag;

                    Pop_NewMessage.ModalOpen();

                }
            }
        }

        protected void Pop_NewMessage_UserControlLoaded(object sender, EventArgs e)
        {

        }

        protected void Pop_NewMessage_UserControlCycleError(object sender, EventArgs e)
        {

        }

        protected void Pop_NewMessage_UserControlClosing(object sender, EventArgs e)
        {

            LoadList(false);
        }
        #endregion


        #region this function logic
        public bool listOdd { get; set; }
        public string listClass { get; set; }
        public bool subListOdd { get; set; }
        public string subListClass { get; set; }

        public string GetListClass()
        {
            listOdd = !listOdd;
            return listOdd ? "listNormal" : "listOdd";
        }

        public string GetSubListClass()
        {
            subListOdd = !subListOdd;
            return subListOdd ? "subListNormal" : "subListOdd";
        }



        public string GetAnswer(object dataItem, object replyToId, object discussionId)
        {
            if (dataItem != null && replyToId != null && (Guid)replyToId != (Guid)discussionId)
            {
                Message RM = (Message)dataItem;
                if (RM != null)
                {
                    string messageText = RM.MessageText;
                    string user = RM.UserProfile.FirstName + " " + RM.UserProfile.LastName;
                    if (messageText.Length > 50)
                    {
                        messageText = messageText.Remove(50) + "...";
                    }

                    return "@:" + user + "  [" + messageText + "]";
                }
            }
            return "";
        }


        #endregion

    }
}